/**
 * Created by fanxu on 16/4/28.
 */
$(function(){
    var myVid = document.getElementById("musicBox");
    myVid.onstalled = function() {
        myVid.load();
    };
});

var SHAKE_THRESHOLD = 2000;
var last_update = 0,shake_count=0;
var ajax_url='http://643713.ichengyun.net/LaneWeChat/record.php',isAjax=false;
var x = 0, y = 0, z = 0, last_x = 0, last_y = 0, last_z = 0;
function init() {
    if (window.DeviceMotionEvent) {
        window.addEventListener('devicemotion', deviceMotionHandler, false);
    } else {
        alert('not support mobile event');
    }
}
function deviceMotionHandler(eventData) {
    var acceleration = eventData.accelerationIncludingGravity;
    var curTime = new Date().getTime();

    if ((curTime - last_update) > 100) {
        shake_count++;
        var diffTime = curTime - last_update;
        last_update = curTime;
        x = acceleration.x;
        y = acceleration.y;
        z = acceleration.z;
        var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
        var openid = $('#content').attr('openid');

        if (speed > SHAKE_THRESHOLD) {
            var myVid = document.getElementById("musicBox");
            myVid.load();
            myVid.play();

            if(openid=='')return false;
            if( isAjax ) return false;
            isAjax = true;
            $.ajax({url:ajax_url,type:'post',
                dataType:'json',data:{
                shakeCount:shake_count,
                openid:openid
            },
            error:function(data){
                isAjax = false;
            }
            }).done(
                function(data){
                    isAjax = false;
                }
            );
        }
        last_x = x;
        last_y = y;
        last_z = z;
    }
}